 const baseUrl = 'https://chezhu.prd4.weiniaokeji.cn'
import Toast from '@vant/weapp/toast/toast';

const exceptionAddrArr = [
  '/c_api/phoneLogin',
  '/c_api/pwdLogin',
  '/c_api/register',
  '/sms/send',
];

function CreateHeader(url) {
  let header = {}
  header = {
    'content-type': 'application/json'
  }
  if (exceptionAddrArr.indexOf(url) == -1) { //排除请求的地址不须要token的地址
    header['x-token'] = wx.getStorageSync('token');
  }
  return header;
}

export function request({
  url,
  method = "GET",
  data,
  isLoding = true
}) {
  let fullUrl = baseUrl + url
  let header = CreateHeader(url);
  if (isLoding) {
    wx.showLoading({
      title: '加载中...'
    })
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: fullUrl,
      method,
      data,
      header,
      success(res) {
        console.log(res)
        const code = res.data.code
        console.log(code)
        if (code == 401) {
          if (isLoding) {
            wx.hideLoading()
          }
          wx.showModal({
            title: '提示：',
            content: "登录失效，请重新登录",
            showCancel: false,
            confirmText: '重新登录',
            success: () => {
              wx.navigateTo({
                url: '/pages/authorize/login/login',
              })
              wx.setStorageSync('token', null)
            }
          })
          return
        }
        if (code == 0) {
          if (isLoding) {
            wx.hideLoading()
          }
          resolve(res)
        } else  {
          if (isLoding) {
            wx.hideLoading()
          }
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000
          })
          reject(res)

        }
      },
      fail(error) {
        console.log(error)
        if (isLoding) {
          wx.hideLoading()
        }
        wx.showToast({
          title: error.msg,
        })
        reject(error)
      }
    })
  })

}